package poolserver

import (
	"encoding/binary"
	"net"

	"fmt"
)

func sendPqReadyForQuery(conn net.Conn, transState byte) error {
	var buf [6]byte
	buf[0] = 'Z'
	binary.BigEndian.PutUint32(buf[1:], 5)
	buf[5] = transState
	_, err := sendData(conn, buf[:6])
	return err
}

func sendPqErrorResponse(conn net.Conn, errFields []string) error {
	var buf = make([]byte, 5, 128)
	buf[0] = 'E'
	binary.BigEndian.PutUint32(buf[1:], 0)
	for _, ef := range errFields {
		buf = append(buf, []byte(ef)...)
		buf = append(buf, 0)
	}
	buf = append(buf, 0)
	binary.BigEndian.PutUint32(buf[1:], uint32(len(buf)-1))
	_, err := sendData(conn, buf)
	return err
}

/*
func sendPqParseCompletion(conn net.Conn) error {
	var recvBuf [5]byte
	recvBuf[0] = '1'
	binary.BigEndian.PutUint32(recvBuf[1:], 4)
	_, err := sendData(conn, recvBuf[:5])
	return err
}*/

func sendPqCloseCompletion(conn net.Conn) error {
	var buf [5]byte
	buf[0] = '3'
	binary.BigEndian.PutUint32(buf[1:], 4)
	_, err := sendData(conn, buf[:5])
	return err
}

func sendPqClosePrepare(conn net.Conn, prepareId int32) error {
	var buf = make([]byte, 0, 12)
	buf = append(buf, 'C', 0, 0, 0, 0, 'S')
	buf = append(buf, []byte(fmt.Sprintf("S%d", prepareId))...)
	buf = append(buf, 0)
	binary.BigEndian.PutUint32(buf[1:], uint32(len(buf)-1))
	_, err := sendData(conn, buf)
	return err
}

func sendPqSync(conn net.Conn) error {
	var buf [5]byte
	buf[0] = 'S'
	binary.BigEndian.PutUint32(buf[1:], 4)
	_, err := sendData(conn, buf[:])
	return err
}

func sendRollback(conn net.Conn) error {
	var buf [15]byte
	buf[0] = 'Q'
	binary.BigEndian.PutUint32(buf[1:], 14)
	copy(buf[5:], "rollback;")
	buf[14] = 0
	_, err := sendData(conn, buf[:])
	return err
}

func printBackendErrorMessage(buf []byte) {
	var pos int32
	var begin int32
	var dataLen int32
	dataLen = int32(binary.BigEndian.Uint32(buf[1:5]))
	begin = 5
	pos = begin
	for pos < dataLen+1 {
		for ; pos < dataLen+1 && buf[pos] != 0; pos++ {
		}
		if pos-begin < 2 {
			return
		}
		//TCHDEBUG zap.S().Infof("%c(%s)", buf[begin], string(buf[begin+1:pos]))
		pos++
		begin = pos
	}
}
